package com.sailboard.iot.opm.web.controller;

import com.sailboard.iot.opm.common.SystemCodeConstants;
import com.sailboard.iot.opm.service.qrcode.OssUtil;
import com.sailboard.iot.opm.utils.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
public class AttachmentUtil {
	/**
	 * 上传文件并保存
	 */
	public static String saveAttachments(MultipartFile file,String fileNameOld){
		//String fileUploadPath= SystemCodeConstants.STATIC_FILE_URL+"/";//本地测试协议上传路径
		String fileUploadPath= SystemCodeConstants.STATIC_FILE_URL+File.separator;//OSS协议上传路径
		String tempPath=SystemCodeConstants.STATIC_UPLOAD_URL_BD;//本地服务器临时文件路径上传路径
		if(StringUtils.isNotBlank(fileUploadPath)){
				//创建目录
				String fileType=null;
				String fileNameNew=null;
		    			//保存附件信息
			    fileType=fileNameOld.substring(fileNameOld.lastIndexOf(".")+1);
			    fileNameNew= UUID.randomUUID().toString()+"."+fileType;
			  //将上传的文件保存到临时文件夹下
			   File tempFolder = new File(tempPath);
			  if (!tempFolder.exists()) {
				tempFolder.mkdirs();
			   }
			  File tempFile = new File(tempPath+ File.separator+ fileNameNew);
			//将上传的文件保存到临时文件夹下
			try {
				file.transferTo(tempFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			    //上传文件
			    String uploadFileName=fileUploadPath+fileNameNew;
//		        File uploadFile=new File(uploadFileName);
//			    FileUtil.copy(tempFile, uploadFile);
			/**
			 * 切换阿里云oss存储方式
			 */
			OssUtil.uploadToOss(tempFile, uploadFileName);
			  tempFile.delete();
			    return fileNameNew;
		}
		return null;
	}
	/**
	 * 校验文件格式是否有问题
	 * @param bType
	 */
	public static boolean checkAttachments(String bType,String filename){
		// 判断是否为白名单内上传文件类型
	    boolean flag=false;
	    String[] allowedUploadTypes={"doc","docx","txt","pdf","xls","xlsx"};
		String fileType=null;
	    		flag=false;
	    			fileType=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
	    			for(String s:allowedUploadTypes){
	    				if(fileType.contains(s.toUpperCase())){
	    					flag=true;
	    					break;
	    				}
	    			}
	    			if(!flag){
	    				return false;
	    			}
	    return true;
	}
}
